<!-- 回复列表 -->
<template>
  <div>
    <a-card id="comment">
      <a-config-provider>
        <template v-if="listData.length === 0" #renderEmpty>
          <div style="text-align: center">
            <a-icon type="smile" style="font-size: 20px" />
            <p style="margin-top: 5px;">暂且没有人评论哦</p>
          </div>
        </template>
        <a-list
          item-layout="vertical"
          size="large"
          :pagination="pagination"
          :data-source="listData"
        >
          <!-- 顶级评论 -->
          <a-list-item
            slot="renderItem"
            key="item.title"
            slot-scope="item, index"
          >
            <a-comment>
              <template slot="actions">
                <span>
                  <a-icon type="calendar" style="margin-right: 8px;" />
                  {{ item.createTime }}
                </span>
                <span
                  @click="userOperaAction(item.id, 'praise', item.isPraise)"
                >
                  <a-icon
                    type="like"
                    style="margin-right: 8px;"
                    :style="{ color: item.isPraise ? 'red' : '' }"
                  />
                  {{ item.praise }}
                </span>
                <span
                  @click="userOperaAction(item.id, 'unpraise', item.isUnpraise)"
                >
                  <a-icon
                    type="dislike"
                    style="margin-right: 8px;"
                    :style="{ color: item.isUnpraise ? 'red' : '' }"
                  />
                  {{ item.unpraise * -1 }}
                </span>
                <span style="margin-right: 8px;" @click="replyDialog(item)"
                  >回复</span
                >
              </template>
              <a slot="author" @click="getUser(item.userId)">
                <a-avatar
                  :src="item.avatar ? item.avatar : ''"
                  :style="{
                    backgroundColor: item.avatar ? 'white' : 'green',
                    verticalAlign: 'middle',
                  }"
                >
                  {{ item.userName }}
                </a-avatar>
                <span style="cursor: pointer; margin-left:10px;">{{ item.userName }}</span>
              </a>
              <p slot="content" style="text-indent:2em;">{{ item.commentTxt }}</p>
              <!-- 子级评论 -->
              <template v-for="childItem in item.childrenComment">
                <a-comment :key="childItem.id">
                  <template slot="actions">
                    <span>
                      <a-icon type="calendar" style="margin-right: 8px;" />
                      {{ childItem.createTime }}
                    </span>
                    <span
                      @click="
                        userOperaAction(
                          childItem.id,
                          'praise',
                          childItem.isPraise
                        )
                      "
                    >
                      <a-icon
                        type="like"
                        style="margin-right: 8px;"
                        :style="{ color: childItem.isPraise ? 'red' : '' }"
                      />
                      {{ childItem.praise }}
                    </span>
                    <span
                      @click="
                        userOperaAction(
                          childItem.id,
                          'unpraise',
                          childItem.isUnpraise
                        )
                      "
                    >
                      <a-icon
                        type="dislike"
                        style="margin-right: 8px;"
                        :style="{ color: childItem.isUnpraise ? 'red' : '' }"
                      />
                      {{ childItem.unpraise * -1 }}
                    </span>
                    <span
                      style="margin-right: 8px;"
                      @click="replyDialog(item, childItem)"
                      >回复</span
                    >
                  </template>

                  <a slot="author" @click="getUser(item.userId)">
                    <a-avatar
                      :src="childItem.avatar ? childItem.avatar : ''"
                      :style="{
                        backgroundColor: childItem.avatar ? 'white' : 'green',
                        verticalAlign: 'middle',
                      }"
                    >
                      {{ childItem.userName }}
                    </a-avatar>
                  </a>
                  <a slot="author" style="cursor: pointer; margin-left:10px;">{{ childItem.userName }}</a>
                  <a
                    slot="author"
                    :style="{ color: 'blue' }"
                    v-if="childItem.atUser !== ''"
                  >
                    <template v-if="item.userName !== childItem.atUser"
                      >@ {{ childItem.atUser }}</template
                    >
                  </a>

                  <p slot="content" style="text-indent:2em;">{{ childItem.commentTxt }}</p>
                </a-comment>
              </template>
              <!-- 子级评论分页 -->
              <a-pagination
                :hideOnSinglePage="true"
                size="small"
                :total="item.childrenComment.length"
                :page-size="childPagination.pageSize"
                :show-total="(total) => `共 ${total} 条回复`"
              />
              <!-- 回复框 -->
              <template>
                <a-form-model id="commentChild" v-if="item.visiable">
                  <a-form-model-item>
                    <a-input
                      :placeholder="item.placeholder"
                      type="textarea"
                      v-model="form.commentText"
                      :style="{
                        marginTop: '10px',
                        height: '150px',
                        resize: 'none',
                      }"
                    />
                  </a-form-model-item>
                  <a-form-model-item>
                    <a-button
                      type="primary"
                      @click="onSubmit(item)"
                      :style="{ float: 'right' }"
                      >回复</a-button
                    >
                  </a-form-model-item>
                </a-form-model>
              </template>
            </a-comment>
          </a-list-item>
        </a-list>
      </a-config-provider>
    </a-card>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import ReplyModal from "@/components/Modal/ReplyModal";
import { publish, getList } from "@/apis/comment";
import { updateAction, getUserOperaList } from "@/apis/commentAction";
import { getToken } from "@/utils/auth";
export default {
  // import引入的组件需要注入到对象中才能使用
  components: { ReplyModal },
  data() {
    // 这里存放数据
    return {
      listData: [],
      reply: false,
      pagination: {
        hideOnSinglePage: true,
        onChange: (page) => {
          let $this = $(window);
          let duration = 30;
          let targetHight = $("#comment").offset().top;
          let timer;
          function animation() {
            if ($this.scrollTop() > targetHight) {
              timer = setTimeout(() => {
                $this.scrollTop($this.scrollTop() - duration);
                if ($this.scrollTop() > targetHight) animation();
              }, 0.05);
            }
            $(window).on("mousewheel DOMMouseScroll", function(event) {
              let delta =
                (event.originalEvent.wheelDelta &&
                  (event.originalEvent.wheelDelta > 0 ? 1 : -1)) || // chrome & ie
                (event.originalEvent.detail &&
                  (event.originalEvent.detail > 0 ? -1 : 1)); // firefox
              // 向下滚
              if (delta < 0) {
                //do somthing
                window.clearTimeout(timer);
              }
            });
          }
          animation();
        },
        pageSize: 10,
      },
      childPagination: {
        pageSize: 5,
      },
      form: {
        commentText: "",
        articleId: 0,
        parentCommentId: 0,
      },
      visiable: false,
    };
  },
  // 监听属性 类似于data概念
  computed: {
    refresh() {
      return this.$store.getters.commentRefresh;
    },
    userId() {
      return parseInt(this.$store.getters.id);
    },
  },
  //监控data中的数据变化
  watch: {
    refresh(nv, ov) {
      this.commentList();
    },
    getUser(id) {
      this.$router.push("/User/"+id);
    },
  },
  //方法集合
  methods: {
    replyModal() {
      this.reply = true;
    },
    replyTag(tag) {
      this.reply = tag;
    },
    commentList() {
      let data = {
        page: 1,
        limit: 5,
        articleId: this.$route.params.id,
      };
      getList(data).then((res) => {
        this.listData = res.data.list;
        this.editListData();
      });
    },
    onSubmit(that) {
      publish(this.form).then((res) => {
        this.$message.success(res.msg);
        this.commentList();
        this.form = {
          commentText: "",
          articleId: 0,
          parentCommentId: 0,
        };
        this.$nextTick(() => {
          let targetHeight = $("#commentChild").offset().top;
          let nowHeight = $(window).scrollTop();
          if (nowHeight < targetHeight) {
            $(window).scrollTop(targetHeight - 200);
          }
        });
      });
    },
    replyDialog(that, child) {
      // 判断数据存储数据类型
      let articleId = this.$route.params.id;
      let parentCommentId = child === undefined ? that.id : child.id;
      this.form.articleId = articleId;
      this.form.parentCommentId = parentCommentId;
      // @ 符号的判定，顶级不显示
      this.listData
        .filter((i) => i.visiable === true)
        .forEach((i) => (i.visiable = false));
      that.visiable = true;
      if (child) {
        that.placeholder = "@ " + child.userName;
      } else {
        that.placeholder = "";
      }
      // 渲染后执行
      this.$nextTick(() => {
        let targetHeight = $("#commentChild").offset().top;
        let nowHeight = $(window).scrollTop();
        if (nowHeight < targetHeight) {
          $(window).scrollTop(targetHeight - 200);
        }
      });
    },
    editListData() {
      let obj = this.listData;
      let that = this;
      obj.map((i) => {
        that.$set(i, "visiable", false);
        that.$set(i, "placeholder", "");
        that.$set(i, "isPraise", false);
        that.$set(i, "isUnpraise", false);
      });
      if (getToken()) {
        getUserOperaList(this.userId).then((res) => {
          let operaList = res.data;
          operaList.forEach((element) => {
            obj.forEach((v) => {
              if (element.commentId === v.id) {
                this.$set(v, "isPraise", element.isPraise);
                this.$set(v, "isUnpraise", element.isUnpraise);
              }
              if (v.childrenComment.length > 0) {
                let childrens = v.childrenComment;
                childrens.forEach((c) => {
                  if (element.commentId === c.id) {
                    this.$set(c, "isPraise", element.isPraise);
                    this.$set(c, "isUnpraise", element.isUnpraise);
                  }
                });
              }
            });
          });
        });
      }

      this.listData = obj;
    },
    userOperaAction(id, method, opera) {
      let data = {
        commentId: id,
        userId: this.userId,
      };
      if (method === "unpraise") {
        this.$set(data, "isUnpraise", !opera);
      }
      if (method === "praise") {
        this.$set(data, "isPraise", !opera);
      }
      updateAction(data).then((res) => {
        if (res.data) {
          this.commentList();
        }
      });
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.commentList();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="scss" scoped>
//@import url(); 引入公共css类
</style>
